import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: LeetCode
 * @description: LeetCode : 116. 填充每个节点的下一个右侧节点指针
 * @author: WXY
 * @create: 2023-03-08 13:57
 * @Version 1.0
 **/
public class Num116_connect {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };
    public Node connect1(Node root) {
        process(root);
        return root;
    }

    private void process(Node root) {
        if (root == null)return;
        if (root.left != null) {
            root.left.next = root.right;
        }
        if (root.right != null) {
            if (root.next != null) {
                root.right.next = root.next.left;
            } else {
                root.right.next = null;
            }
        }
        process(root.left);
        process(root.right);
    }

    public Node connect(Node root) {
       if (root ==null) return root;
        Queue<Node> que = new LinkedList<Node>();
        que.offer(root);
        Node nodePre = null;
        Node node = null;
        while (!que.isEmpty()) {
            int size = que.size();
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    nodePre = que.peek();
                    que.poll();
                    node = nodePre;
                } else {
                    node = que.peek();
                    que.poll();
                    nodePre.next = node;
                    nodePre = nodePre.next;
                }
                if (node.left != null) que.offer(node.left);
                if (node.right!= null) que.offer(node.right);
            }
            nodePre.next = null;
        }
        return root;
    }
}
